<template>
  <div class="patrol-task-container">
    <!-- 页面头部 -->
    <div class="patrol-header">
      <h2 class="page-title">巡更任务管理</h2>
      <div class="filter-container">
        <el-select
            v-model="filters.status"
            placeholder="选择任务状态"
            @change="handleFilterChange"
            class="filter-select"
        >
          <el-option value="" label="全部状态"></el-option>
          <el-option value="0" label="未开始"></el-option>
          <el-option value="1" label="进行中"></el-option>
          <el-option value="2" label="已完成"></el-option>
          <el-option value="3" label="已暂停"></el-option>
          <el-option value="4" label="已取消"></el-option>
          <el-option value="5" label="执行失败"></el-option>
        </el-select>

        <el-select
            v-model="selectedCommunity"
            placeholder="选择社区"
            @change="handleCommunityChange"
        >
          <el-option value="" label="请选择社区"></el-option>
          <el-option
              v-for="community in communityList"
              :key="community.id"
              :value="community.id"
              :label="community.name"
          ></el-option>
        </el-select>

        <el-button
            type="primary"
            class="create-btn"
            @click="createTask"
            icon="Plus"
        >
          创建任务
        </el-button>
      </div>
    </div>

    <!-- 统计卡片  -今日任务总数（添加点击事件）  -->
    <div class="stats-container">
      <el-card class="stat-card" :shadow="hover" @mouseenter="hover = 'hover'" @mouseleave="hover = 'always'" @click="openTaskDetailDialog">
        <div class="stat-item">
          <div class="stat-label">今日任务总数</div>
          <div class="stat-value">{{ taskStats.total || 0 }}</div>
          <div class="stat-icon blue-icon">
            <el-icon><Document /></el-icon>
          </div>
        </div>
      </el-card>

      <!-- 任务明细弹窗 -->
      <el-dialog
          title="今日任务明细"
          v-model="taskDetailDialogVisible"
          width="950px"
          :close-on-click-modal="false"
      >
        <el-table
            :data="tasks"
            border
            stripe
            style="width: 100%"
        >
          <el-table-column prop="planName" label="任务名称" width="200" />
          <el-table-column prop="communityName" label="所属社区" width="150" />
          <el-table-column prop="executorName" label="执行人" width="120" />
          <el-table-column label="计划时间" width="200">
            <template #default="scope">
              {{ formatDateTime(scope.row.plannedStartTime) }}至{{ formatDateTime(scope.row.plannedEndTime, true) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.taskStatus)">
                {{ getStatusDesc(scope.row.taskStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleViewDetail(scope.row.taskId)"
                  icon="View"
              >
                处理
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <el-card class="stat-card" :shadow="hover" @mouseenter="hover = 'hover'" @mouseleave="hover = 'always'">
        <div class="stat-item">
          <div class="stat-label">进行中任务</div>
          <div class="stat-value">{{ taskStats.ongoing }}</div>
          <div class="stat-icon yellow-icon">
            <el-icon><Clock /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" :shadow="hover" @mouseenter="hover = 'hover'" @mouseleave="hover = 'always'">
        <div class="stat-item">
          <div class="stat-label">已完成任务</div>
          <div class="stat-value">{{ taskStats.completed }}</div>
          <div class="stat-icon green-icon">
            <el-icon><CircleCheck /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" :shadow="hover" @mouseenter="hover = 'hover'" @mouseleave="hover = 'always'">
        <div class="stat-item">
          <div class="stat-label">未完成任务</div>
          <div class="stat-value">{{ taskStats.unfinished }}</div>
          <div class="stat-icon red-icon">
            <el-icon><CircleClose /></el-icon>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card" :shadow="hover" @mouseenter="hover = 'hover'" @mouseleave="hover = 'always'">
        <div class="stat-item">
          <div class="stat-label">逾期任务</div>
          <div class="stat-value">{{ taskStats.failed || 0 }}</div>
          <div class="stat-icon red-icon">
            <el-icon><Warning /></el-icon>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 生成任务按钮 -->
    <el-button
        v-if="canGenerateTodayTasks"
        type="warning"
        class="generate-btn"
        @click="generateTodayTasks"
        icon="RefreshRight"
    >
      手动生成今日任务
    </el-button>

    <!-- 任务表格 -->
    <el-card class="table-card">
      <el-table
          :data="tasks"
          border
          stripe
          style="width: 100%;"
          v-loading="loading"
          :header-cell-style="{background:'#f5f7fa', color:'#606266', fontWeight: 'bold'}"
      >
        <el-table-column prop="planName" label="任务名称" width="200" />
        <el-table-column prop="communityName" label="所属社区" width="150" />
        <el-table-column label="执行人" width="160">
          <template #default="scope">
            <div class="executor-info">
              <el-avatar
                  :src="getAvatarUrl(scope.row.executorId)"
                  class="executor-avatar"
                  size="small"
              />
              <span class="executor-name">{{ scope.row.executorName || '未指定' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="计划时间" width="220">
          <template #default="scope">
            <div>{{ formatDateTime(scope.row.plannedStartTime) }}</div>
            <div class="time-range">至 {{ formatDateTime(scope.row.plannedEndTime, true) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag
                :type="getStatusTagType(scope.row.taskStatus)"
                size="small"
            >
              {{ getStatusDesc(scope.row.taskStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="完成率" width="120">
          <template #default="scope">
            <div class="completion-rate" v-if="scope.row.taskStatus === 2">
              <el-progress
                  :percentage="Number(scope.row.completionRate || 0)"
                  stroke-width="6"
                  :show-text="false"
              />
              <span class="rate-text">{{ Number(scope.row.completionRate || 0).toFixed(1) }}%</span>
            </div>
            <div v-else class="rate-text">-</div>
          </template>
        </el-table-column>
        <el-table-column label="关联路线" min-width="150">
          <template #default="scope">
            <div
                v-for="(route, index) in getRouteList(scope.row.routeIds)"
                :key="index"
                class="route-item"
            >
              <span class="route-dot" :style="{backgroundColor: getRouteColor(index)}"></span>
              路线{{ route }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope"> <!-- 表格作用域插槽，scope 有效 -->
            <!-- 原有按钮：详情、开始、暂停、取消、导出 -->
            <el-button
                size="small"
                v-if="scope.row.taskStatus === 0"
                type="success"
                @click="handleViewDetail(scope.row.taskId)"
                icon="Play"
            >
              开始
            </el-button>

            <el-button
                size="small"
                v-if="scope.row.taskStatus === 1"
                type="warning"
                @click="handlePauseTask(scope.row.taskId)"
                icon="Pause"
            >
              暂停
            </el-button>

            <!-- 新增：继续按钮（仅在“已暂停”状态显示） -->
            <el-button
                size="small"
                v-if="scope.row.taskStatus === 3"
                type="success"
                @click="handleResumeTask(scope.row.taskId)"
                icon="Play"
            >
              继续
            </el-button>

            <el-button
                size="small"
                v-if="scope.row.taskStatus === 0 || scope.row.taskStatus === 1 || scope.row.taskStatus === 3"
                type="danger"
                @click="handleCancelTask(scope.row.taskId)"
                icon="Delete"
            >
              取消
            </el-button>

            <el-button
                size="small"
                v-if="scope.row.taskStatus === 2"
                type="info"
                @click="handleExportReport(scope.row.taskId)"
                icon="Download"
            >
              导出
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 空状态 -->
    <div v-if="tasks.length === 0 && !loading" class="empty-state">
      <el-empty
          description="暂无巡更任务数据"
          :image-size="120"
      >
        <template #bottom>
          <el-button
              type="primary"
              @click="generateTodayTasks"
              v-if="canGenerateTodayTasks"
          >
            生成今日任务
          </el-button>
        </template>
      </el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
      ></el-pagination>
    </div>

    <!-- 任务详情弹窗 -->
    <el-dialog
        title="任务详情"
        v-model="detailDialogVisible"
        width="700px"
        :close-on-click-modal="false"
    >
      <!-- 关键修复：将 taskId 转换为字符串 -->
      <task-detail :task-id="currentTaskId" @close="detailDialogVisible = false" />
    </el-dialog>

    <!-- 移动端任务列表 -->
    <div class="mobile-task-list" v-if="isMobile">
      <div class="mobile-task-item" v-for="task in tasks" :key="task.taskId">
        <div class="task-header">
          <div class="task-name">{{ task.planName }}</div>
          <el-tag :type="getStatusTagType(task.taskStatus)">{{ getStatusDesc(task.taskStatus) }}</el-tag>
        </div>
        <div class="task-info">
          <div class="info-item">
            <span class="info-label">社区:</span>
            <span class="info-value">{{ task.communityName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">执行人:</span>
            <span class="info-value">{{ task.executorName || '未指定' }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">时间:</span>
            <span class="info-value">{{ formatDateTime(task.plannedStartTime) }}-{{ formatDateTime(task.plannedEndTime, true) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">完成率:</span>
            <span class="info-value" v-if="task.taskStatus === 2">{{ Number(task.completionRate || 0).toFixed(1) }}%</span>
            <span class="info-value" v-else>-</span>
          </div>
          <div class="info-item">
            <span class="info-label">路线:</span>
            <span class="info-value">
              <span v-for="(route, index) in getRouteList(task.routeIds)" :key="index" class="route-tag">
                路线{{ route }}
              </span>
            </span>
          </div>
        </div>
        <div class="task-actions">
          <el-button
              size="mini"
              type="primary"
              @click="handleViewDetail(task.taskId)"
          >
            详情
          </el-button>
          <el-button
              size="small"
              v-if="task.taskStatus === 0"
              type="success"
              @click="handleViewDetail(scope.row.taskId)"
          >
            开始
          </el-button>
          <el-button
              size="small"
              v-if="task.taskStatus === 1"
              type="warning"
              @click="handlePauseTask(task.taskId)"
          >
            暂停
          </el-button>
          <!-- 新增：继续按钮，仅在“已暂停”状态显示 -->
          <el-button
              size="small"
              v-if="scope.row.taskStatus === 3"
          type="success"
          @click="handleResumeTask(scope.row.taskId)"
          icon="Play"
          >
          继续
          </el-button>
          <el-button
              size="small"
              v-if="task.taskStatus === 0 || task.taskStatus === 1"
              type="danger"
              @click="handleCancelTask(task.taskId)"
          >
            取消
          </el-button>
          <el-button
              size="small"
              v-if="task.taskStatus === 2"
              type="info"
              @click="handleExportReport(task.taskId)"
          >
            导出
          </el-button>
        </div>
      </div>
    </div>
  </div>
  <router-view/>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick, computed, watch, onUnmounted} from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import {
  Document, Clock, CircleCheck, CircleClose, Plus, Search,
  RefreshRight, View, Delete, Download, Warning
} from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

// 导入API
import {
  generateDailyTasks,
  updateTaskStatus,
  getTodayTasks,
  calculateCompletionRate,
  getTaskDetail,
  getTaskStats,
  checkCanGenerateTodayTasks,
  exportTaskReport,
  exportAllTasks, getOverdueTasksCount
} from '../api/PatrolTask';
import { getCommunityList } from '../api/community';

// 导入组件
import TaskDetail from '../patrol/TaskDetail.vue';

// 路由
const router = useRouter();
// 继续任务逻辑
const handleResumeTask = async (taskId) => {
  await updateStatus(taskId, 1, '手动继续任务'); // 状态改为“进行中”
};
// 响应式数据
const tasks = ref([]);
const loading = ref(false);
const communityList = ref([]);
const selectedCommunity = ref('');
const detailDialogVisible = ref(false);
const currentTaskId = ref(null);
const hover = ref('always');
const isMobile = ref(false);
const total = ref(0);
const overdueCount = ref(0); // 逾期任务数
// 响应式变量：控制任务明细弹窗显示
const taskDetailDialogVisible = ref(false);
const taskDetailList = ref([]);
// 打开任务明细弹窗
const openTaskDetailDialog = () => {
  console.log('点击事件触发，当前任务总数:', taskStats.total);
  if (taskStats.total === 0) {
    ElMessage.info("当前无任务数据");
    return;
  }
  taskDetailDialogVisible.value = true;
  loadTodayTaskDetailsForDialog(); // 加载弹窗专用数据
};
const loadTodayTaskDetailsForDialog = async () => {
  try {
    loading.value = true;
    const params = {
      communityId: selectedCommunity.value ? Number(selectedCommunity.value) : 0,
      date: new Date().toISOString().split('T')[0]
    };
    console.log('弹窗任务明细参数:', params);
    let {data:data} = await getTodayTasks(params);
    console.log('弹窗任务明细返回:', data);

    if (data.code === 0) {
      taskDetailList.value = data.data.records;
      if (taskDetailList.value.length === 0) {
        ElMessage.info('今日无任务明细数据');
      }
    } else {
      ElMessage.error(data.message || '获取任务明细失败');
      taskDetailList.value = [];
    }
  } catch (error) {
    console.error('弹窗任务明细加载失败:', error);
    ElMessage.error('获取任务明细失败，请稍后重试');
    taskDetailList.value = [];
  } finally {
    loading.value = false;
  }
};
// 添加任务明细数据加载方法
const loadTodayTaskDetails = async () => {
  try {
    loading.value = true;
    const params = {
      // 社区ID：确保传递正确格式（后端可能要求0表示全部，而非null）
      communityId: selectedCommunity.value ? Number(selectedCommunity.value) : 0,
      date: new Date().toISOString().split('T')[0] // 格式如 "2025-07-19"
    };
    console.log('请求任务明细参数:', params); // 打印参数确认
    let {data:data} = await getTodayTasks(params);
    console.log('任务明细接口返回:', data); // 打印接口返回完整数据

    if (data.code === 0) {
      tasks.value = Array.isArray(data.data) ? data.data : [];
      // 即使返回空数组，也明确提示
      if (tasks.value.length === 0) {
        ElMessage.info('当前条件下无任务明细数据');
      }
    } else {
      ElMessage.error(data.message || '获取任务明细失败');
      tasks.value = [];
    }
  } catch (error) {
    console.error('任务明细加载失败:', error);
    ElMessage.error('获取任务明细失败，请稍后重试');
    tasks.value = [];
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗（复用现有详情弹窗逻辑）
const handleCloseDialog = () => {
  taskDetailDialogVisible.value = false;
};
// 筛选条件
const filters = reactive({
  status: '',
  keyword: ''
});

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 任务统计
const taskStats = reactive({
  total: 0,
  ongoing: 0,
  completed: 0,
  unfinished: 0
});

// 能否生成今日任务
const canGenerateTodayTasks = ref(false);

// 检测屏幕尺寸
const checkScreenSize = () => {
  isMobile.value = window.innerWidth < 768;
};
// 加载逾期任务数
const loadOverdueTasksCount = async () => {
  try {
    if (!selectedCommunity.value) return; // 未选择社区时不加载
    const params = {
      communityId: Number(selectedCommunity.value) // 传递当前选中的社区ID
    };
    let {data:data} = await getOverdueTasksCount(params);
    if (data.code === 0) {
      overdueCount.value = data.data.total || 0; // 从接口返回的total中取数
    }
  } catch (error) {
    console.error('获取逾期任务数失败:', error);
    overdueCount.value = 0;
  }
};
// 加载任务数据
const loadTasks = async () => {
  try {
    loading.value = true;
    const params = {
      communityId: selectedCommunity.value ? Number(selectedCommunity.value) : 0, // 同明细参数处理
      status: filters.status || '', // 避免传递undefined
      keyword: filters.keyword || '',
      page: pagination.current,
      pageSize: pagination.pageSize
    };
    console.log('主表格请求参数:', params); // 打印参数
    let {data:data} = await getTodayTasks(params);
    console.log('主表格接口返回:', data); // 打印返回数据

    if (data.code === 0) {
      tasks.value = data.data.records;
      pagination.total = data.data.total || 0;
      if (tasks.value.length === 0) {
        ElMessage.info('当前条件下无任务数据');
      }
    } else {
      ElMessage.error(data.message || '获取任务列表失败');
      tasks.value = [];
    }
  } catch (error) {
    console.error('主表格加载失败:', error);
    ElMessage.error('获取任务列表失败，请稍后重试');
    tasks.value = [];
  } finally {
    loading.value = false;
  }
};

// 加载任务统计
const loadTaskStats = async () => {
  try {
    if (!selectedCommunity.value) {
      ElMessage.warning('请先选择社区');
      return;
    }
    const params = {
      date: new Date().toISOString().split('T')[0],  // 传递日期参数
      communityId: Number(selectedCommunity.value)
    };
    let {data:data} = await getTaskStats(params);
    console.log('统计接口返回:', data);

    if (data.code === 0) {
      // 直接使用后端返回的字段（此时字段名已匹配）
      taskStats.total = Number(data.data?.total) || 0;
      taskStats.ongoing = Number(data.data?.ongoing) || 0;
      taskStats.completed = Number(data.data?.completed) || 0;
      taskStats.failed = data.data.failed || 0;  // 逾期任务数（状态5）
      taskStats.unfinished = Number(data.data?.unfinished) || 0;
    } else {
      ElMessage.error('获取统计数据失败: ' + data.message);
    }
  } catch (error) {
    console.error('统计接口请求失败:', error);
  }
};

// 检查是否可以生成今日任务
const checkGeneratePermission = async () => {
  try {
    if (!selectedCommunity.value) {
      ElMessage.warning('请先选择社区');
      return;
    }
    let {data:data} = await checkCanGenerateTodayTasks({
      communityId: Number(selectedCommunity.value)  // 确保为数值类型
    });
    console.log('检查生成任务权限',data)
    if (data.code === 0) {
      canGenerateTodayTasks.value = data.data || false;
    }
  } catch (error) {
    console.error('检查生成任务权限失败:', error);
    // 打印详细错误信息
    if (error.response) {
      console.log('错误响应数据:', error.response.data);
      console.log('请求URL:', error.config.url);
      console.log('请求参数:', error.config.params);
    }
  }
};

// 手动生成今日任务
const generateTodayTasks = async () => {
  try {
    ElMessageBox.confirm(
        '确定要手动生成今日巡更任务吗？这可能会创建重复任务。',
        '确认生成',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    ).then(async () => {
      loading.value = true;
      let {data:data} = await generateDailyTasks();
      console.log('生成任务结果',data)
      if (data.code === 0) {
        ElMessage.success(data.message || '今日任务生成成功');
        await loadTasks();
        await loadTaskStats();
        await checkGeneratePermission();
      } else {
        ElMessage.error(data.message || '生成任务失败');
      }
    }).catch(() => {
      // 用户取消操作
    }).finally(() => {
      loading.value = false;
    });
  } catch (error) {
    console.error('生成任务失败:', error);
    ElMessage.error('生成任务失败，请稍后重试');
    loading.value = false;
  }
};
// 加载社区列表
const loadCommunities = async () => {
  try {
    let {data:data} = await getCommunityList();
    console.log('加载社区列表结果', data);
    if (data.code === 0) {
      // 强制转为数组
      communityList.value = Array.isArray(data.data) ? data.data : [];
    } else {
      ElMessage.error('加载社区列表失败：' + (data.message || '未知错误'));
      communityList.value = [];
    }
  } catch (error) {
    console.error('加载社区列表出错：', error);
    ElMessage.error('加载社区列表失败，请稍后重试');
    communityList.value = [];
  }
};
// 更新任务状态
const updateStatus = async (taskId, status, remark = '') => {
  try {
    let {data:data} = await updateTaskStatus({ taskId, status, remark });
    console.log('更新任务状态结果',data)
    if (data.code === 0) {
      ElMessage.success(`任务已${getStatusDesc(status)}`);
      await loadTasks();
      await loadTaskStats();
      return true;
    } else {
      ElMessage.error(data.message || '更新任务状态失败');
      return false;
    }
  } catch (error) {
    console.error('更新任务状态失败:', error);
    ElMessage.error('更新任务状态失败，请稍后重试');
    return false;
  }
};

// 处理开始任务
const handleStartTask = async (taskId) => {
  await updateStatus(taskId, 1, '手动开始任务');
};

// 处理暂停任务
const handlePauseTask = async (taskId) => {
  await updateStatus(taskId, 3, '手动暂停任务');
};

// 处理取消任务
const handleCancelTask = async (taskId) => {
  ElMessageBox.prompt(
      '请输入取消任务的原因',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入原因'
      }
  ).then(({ value }) => {
    updateStatus(taskId, 4, value);
  }).catch(() => {
    // 用户取消输入
  });
};

// 查看任务详情跳转地图页
const handleViewDetail = (taskId) => {
  // 从任务列表中获取当前任务详情
  const currentTask = tasks.value.find(t => t.taskId === taskId);
  if (!currentTask) {
    ElMessage.error('任务数据不存在');
    return;
  }
  // 跳转至PatrolMap.vue并携带任务ID和路线信息
  router.push({
    path: '/map', // 地图页路由
    query: {
      taskId: taskId,
      routeIds: currentTask.routeIds, // 传递关联路线ID
      communityId: selectedCommunity.value
    }
  });
};

// 导出任务报告
const handleExportReport = async (taskId) => {
  try {
    loading.value = true;
    let {data:data} = await exportTaskReport(taskId);
    console.log('导出任务报告结果',data)

    // 处理文件下载
    const blob = new Blob([data.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `巡更任务报告_${taskId}_${new Date().toLocaleDateString()}.xlsx`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success('报告导出成功');
  } catch (error) {
    console.error('导出报告失败:', error);
    ElMessage.error('导出报告失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 创建新任务
const createTask = () => {
  router.push('/patrol/task/create');
};

// 筛选条件变化
const handleFilterChange = () => {
  pagination.current = 1;
  loadTasks();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  loadTasks();
};
// 社区选择变化
const handleCommunityChange = async () => {
  if (!selectedCommunity.value) {
    ElMessage.warning('请选择具体社区查看数据');
    tasks.value = []; // 清空表格数据
    overdueCount.value = 0; // 清空逾期数
    return;
  }
  await loadTaskStats();
  await loadTodayTaskDetails();
  await loadTasks();
  await checkGeneratePermission();
  await loadOverdueTasksCount(); // 加载逾期数
};
// 当前页变化
const handleCurrentChange = (page) => {
  pagination.current = page;
  loadTasks();
};

// 格式化日期时间
const formatDateTime = (dateTime, onlyTime = false) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  if (onlyTime) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取状态描述
const getStatusDesc = (status) => {
  const statusMap = {
    0: '未开始',
    1: '进行中',
    2: '已完成',
    3: '已暂停',
    4: '已取消',
    5: '执行失败'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',      // 未开始-蓝色
    1: 'warning',   // 进行中-黄色
    2: 'success',   // 已完成-绿色
    3: 'primary',   // 已暂停-深蓝色
    4: 'danger',    // 已取消-红色
    5: 'danger'     // 执行失败-红色
  };
  return typeMap[status] || 'info';
};

// 获取路线列表
const getRouteList = (routeIds) => {
  if (!routeIds) return [];
  return routeIds.split(',');
};

// 获取路线颜色
const getRouteColor = (index) => {
  const colors = [
    '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
    '#5CADFF', '#8BC34A', '#FFB74D', '#FF7043', '#B0BEC5',
    '#3D5AFE', '#00E5FF', '#FFEB3B', '#FF5252', '#7E57C2'
  ];
  return colors[index % colors.length];
};

// 获取头像URL
const getAvatarUrl = (userId) => {
  // 实际项目中应该根据用户ID获取头像URL
  // 这里使用占位图
  return `https://picsum.photos/id/${userId || 1}/200/200`;
};

// 组件挂载时
onMounted(async () => {
  checkScreenSize();
  window.addEventListener('resize', checkScreenSize);

  await loadCommunities();

  if (communityList.value.length === 0) {
    ElMessage.warning('未获取到社区数据，请联系管理员配置');
    return;
  }

  // 自动选择第一个社区，但仍提示用户
  selectedCommunity.value = communityList.value[0].id;
  ElMessage.info(`已自动选择社区：${communityList.value[0].name}`);

  await loadTaskStats();
  await checkGeneratePermission();
  await loadTasks();
  await loadOverdueTasksCount(); // 加载逾期数
  // 监听从地图页返回，自动刷新数据
  watch(
      () => router.currentRoute.value.path,
      (newPath) => {
        if (newPath === '/task') {
          nextTick(); // 等待路由切换完成
          loadTaskStats(); // 刷新统计数字
          loadTasks(); // 刷新任务列表
          loadOverdueTasksCount(); // 刷新逾期数
        }
      }
  );
});


// 组件卸载时
onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize);
});
</script>

<style scoped>
.patrol-task-container {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 40px);
  overflow: auto;
}

.patrol-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.page-title {
  font-size: 24px;
  color: #303133;
  margin: 0;
  font-weight: 600;
  margin-right: 24px;
  margin-bottom: 16px;
}

.filter-container {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-select,
.filter-date-picker {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
}

.search-input {
  width: 220px;
}

.create-btn {
  border-radius: 6px;
  padding: 10px 20px;
  background: linear-gradient(135deg, #67C23A 0%, #409EFF 100%);
  border: none;
  transition: all 0.3s ease;
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.generate-btn {
  margin-bottom: 24px;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.generate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}
.orange-icon {
  background-color: rgba(255, 153, 0, 0.1); /* 浅橙色背景 */
  color: #FF9900; /* 橙色图标 */
}
.blue-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.yellow-icon {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.green-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.red-icon {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.executor-info {
  display: flex;
  align-items: center;
}

.executor-avatar {
  margin-right: 8px;
}

.time-range {
  font-size: 12px;
  color: #909399;
}

.completion-rate {
  display: flex;
  align-items: center;
}

.rate-text {
  margin-left: 8px;
  font-size: 12px;
}

.route-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.route-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.empty-state {
  padding: 40px 0;
}

/* 移动端样式 */
.mobile-task-list {
  display: none;
}

@media (max-width: 768px) {
  .mobile-task-list {
    display: block;
  }

  .el-table {
    display: none;
  }

  .patrol-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-container {
    width: 100%;
  }

  .stats-container {
    grid-template-columns: 1fr;
  }

  .mobile-task-item {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  }

  .task-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .task-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .task-info {
    margin-bottom: 12px;
  }

  .info-item {
    display: flex;
    margin-bottom: 8px;
  }

  .info-label {
    width: 80px;
    color: #909399;
    font-size: 13px;
  }

  .info-value {
    flex: 1;
    color: #303133;
  }

  .route-tag {
    display: inline-block;
    background-color: #f0f2f5;
    color: #606266;
    border-radius: 4px;
    padding: 2px 6px;
    margin-right: 6px;
    margin-bottom: 6px;
    font-size: 12px;
  }

  .task-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>